<template>
  <div>
    <el-row :gutter="20">
      <el-col :lg="22" :md="16" :sm="24" :xl="22" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-form inline :model="queryForm" @submit.prevent>
                <el-form-item>
                  <el-input
                    v-model.trim="queryForm.search"
                    clearable
                    :placeholder="translate('请输入名称')"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    :icon="Search"
                    type="primary"
                    @click="fetchData('search')"
                  >
                    {{ translate('查询') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-top-panel>
          </vab-query-form>
          <div class="add">
            <el-button
                v-if="MenuAuth('add')"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
              <el-button type="primary" @click="download()" plain>
                    {{ translate('下载') }}
              </el-button>
              <el-upload
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    :action="action"
                    :before-upload="beforeUpload"
                    class="ml"
                    :headers="headers"
                    name="fileInput"
                    :on-error="handleError"
                    :on-success="handleSuccess"
                    :show-file-list="false"
                  >
              <el-button type="primary" @click="uploadFn()" plain>
                      {{ translate('导入') }}
              </el-button>
              </el-upload>
              <el-button type="primary" @click="exportFn()" plain>
                    {{ translate('导出') }}
              </el-button>
          </div>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            default-expand-all
            min-width="1600px"
            row-key="path"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <!-- <el-table-column label="排序号" prop="SortCode " show-overflow-tooltip /> -->
            <el-table-column
              :label="translate('库位编码')"
              min-width="120"
              prop="Code"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('库位名称')"
              min-width="92"
              prop="FullName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('库位类型')"
              min-width="86"
              prop="SType"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('重量上限')"
              min-width="86"
              prop="WeightLimit"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('体积上限')"
              min-width="86"
              prop="VolumeLimit "
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('补货触发量')"
              min-width="98"
              prop="RTQ"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('补货上限')"
              min-width="86"
              prop="RTLimit"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('物资混放')"
              min-width="86"
              prop="ItemMixup"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('批次混放')"
              min-width="86"
              prop="BatchMixup"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('库位长')"
              prop="SLength"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('库位宽')"
              prop="SWidth"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('库位高')"
              prop="SHeight"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('排')"
              prop="SRow"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('位')"
              prop="SPositon"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('层')"
              prop="SLayer"
              show-overflow-tooltip
            />
            <!-- <el-table-column
              label="创建人"
              prop="CreateUserName "
              show-overflow-tooltip
            />
            <el-table-column
              label="创建时间"
              prop="CreateDate "
              show-overflow-tooltip
            /> -->
            <!-- <el-table-column
                    label="仓库地址"
                    prop="Address"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="详细地址"
                    prop="AddressDetail"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="邮编"
                    prop="PostCode"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="创建人"
                    prop="CreateUserName "
                    show-overflow-tooltip
                  /> -->
            <el-table-column
              :label="translate('是否有效')"
              min-width="86"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.Enabled ? translate('是') : translate('否') }}
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('备注')"
              prop="Remark"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              fixed="right"
              :label="translate('操作')"
              show-overflow-tooltip
              width="180"
            >
              <template #default="{ row }">
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                  plain
                >
                  {{ translate('编辑') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                      class="vab-data-empty"
                      :src="require('@/assets/empty_images/data_empty.png')"
                    /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>
    <edit
      ref="editRef"
      :area-list="areaList"
      :shelf-list="shelfList"
      :store-list="storeList"
      @fetch-data="fetchData"
    />
  </div>
</template>

<script>
  import {
    doDelete,
    getList,
    getData,
    getstoreData,
    getareaData,
    getshelfData,
    Wms_WareHouse_StorageDown,
    Wms_WareHouse_StorageExport,
  } from '@/api/storage'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { useSettingsStore } from '@/store/modules/settings'
  import { MenuAuth } from '~/src/utils/permission'
  import { parseTime } from '@/utils'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'Storage',
    components: {
      Edit: defineAsyncComponent(() => import('./components/StorageEdit')),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        editRef: null,
        list: [],
        areaList: [],
        storeList: [],
        shelfList: [],
        queryTreeForm: {
          pageNo: 1,
          pageSize: 100,
          wheres: `[{"name":"ModuleId","value":"value","displayType":"equal"}]`,
          export: false,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
        },
        queryForm: {
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"ModuleId","value":"value","displayType":"equal"}]`,
          export: false,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        listLoading: true,
        expandDefault: [],
        headers: {},
        action: '',
      })
      //列表编辑
      const handleEdit = (row, type) => {
        if (row && row.SID) {
          state['editRef'].showEdit(row, type)
        } else {
          // if (!row) state['editRef'].showEdit(state.queryForm)
          state['editRef'].showEdit(row, type)
        }
      }
      //页面刷新
      const settingsStore = useSettingsStore()
      const { theme } = storeToRefs(settingsStore)
      const $pub = inject('$pub')
      const refreshRoute = () => {
        $pub('reload-router-view')
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.SID) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await doDelete({
              sid: row.SID,
            })
            //删除列表默认回到第一页
            $baseMessage(message, 'success', 'vab-hey-message-success')
            // refreshRoute()
            fetchData('search')
          })
        }
      }
      //菜单表格
      const fetchData = async (val) => {
        //wheres重新赋值
        const params = JSON.parse(JSON.stringify(state.queryForm))
        //搜索
        if (val == 'search') {
          params.pageNo = 1
          params.wheres = `[{"name":"FullName","value":"${params.search}","displayType":"like"}]`
        } else {
          params.wheres = `[{"name":"FullName","value":"","displayType":"equal"}]`
        }
        state.listLoading = true
        const {
          data: { rows, total },
        } = await getList(params)
        rows.map((row) => {
          let result = ''
          state.storeList.map((item) => {
            if (row.WHID === item.WHID) {
              result = `${item.Code}`
            }
          })
          state.areaList.map((item) => {
            if (row.WHAID === item.WHAID) {
              result += `-${item.Code}`
            }
          })
          state.shelfList.map((item) => {
            if (row.WHSID === item.WHSID) {
              result += `-${item.Code}`
            }
          })
          row.Code = `${result}-${row.Code}`
        })
        state.list = rows
        state.total = total
        state.listLoading = false
      }
      //分页条数切换
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      //分页切换
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const getAreaData = async () => {
        const {
          data: { rows },
        } = await getareaData(state.queryTreeForm)
        state.areaList = rows
      }
      const getStoreData = async () => {
        const {
          data: { rows },
        } = await getstoreData(state.queryTreeForm)
        state.storeList = rows
      }
      const getShelfData = async () => {
        const {
          data: { rows },
        } = await getshelfData(state.queryTreeForm)
        state.shelfList = rows
      }
      // 下载库位管理
      const download = async () => {
        const data = await Wms_WareHouse_StorageDown()
        if (data) {
          console.log(data)
          const blob = new Blob([data])
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = `库位.xlsx`
          link.href = url
          link.click()
        }
      }
      // 导出
      const exportFn = async () => {
        state.listLoading = true
        const data = await Wms_WareHouse_StorageExport(state.queryForm)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.download = `库位${time}.xlsx`
        link.href = url
        link.click()
        state.listLoading = false
      }
      const handleError = () => {}
      const beforeUpload = () => {}
      const uploadFn = async () => {
        state.headers = state.headers = {
          Authorization: `Bearer ${token}`,
        }
        state.action = `${baseURL}/Wms_WareHouse_Storage/Import`
      }
      const handleSuccess = (data) => {
        console.log(data)
        if (data.code === '200') {
          $baseMessage(
            translate('导入成功'),
            'success',
            'vab-hey-message-success'
          )
          fetchData()
        } else {
          $baseMessage(data.message, 'error', 'vab-hey-message-error')
        }
      }
      onMounted(async () => {
        await getStoreData()
        await getAreaData()
        await getShelfData()
        fetchData()
      })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        Delete,
        Plus,
        Search,
        handleCurrentChange,
        handleSizeChange,
        refreshRoute,
        getAreaData,
        getStoreData,
        getShelfData,
        MenuAuth,
        download,
        exportFn,
        handleError,
        uploadFn,
        beforeUpload,
        handleSuccess,
        translate,
      }
    },
  })
</script>
<style lang="scss" scoped>
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .ml {
      display:inline-block;
      margin-right:10px;
      margin-left:10px;
    }
</style>
